import React, {Component} from 'react'
import {DropdownContext} from './DropdownContext'
import * as PopperJS from '@popperjs/core'

interface DropdownProps {
  disabled?: boolean
  direction?: PopperJS.Placement
  id: string
  hover?: 'light'
}

interface DropdownState {
  isOpen: boolean
}

class Dropdown extends Component<DropdownProps, DropdownState> {
  _containerRef: any

  constructor(props: any) {
    super(props)
    this._containerRef = React.createRef()
    this.state = {
      isOpen: false,
    }
  }

  componentDidMount(): void {
    this.getContainer()
  }

  getContainer = (): any => {
    return this._containerRef.current
  }

  toggle = (e: any): void => {
    const {disabled} = this.props
    const {isOpen} = this.state
    if (disabled) {
      return e && e.preventDefault()
    }
    this.setState({isOpen: !isOpen})
  }

  getContextValue = (): any => {
    const {direction, disabled, id} = this.props
    const {isOpen} = this.state
    return {
      toggle: this.toggle,
      isOpen: isOpen,
      direction: direction ? direction : 'right-start',
      disabled: disabled,
      containerRef: this._containerRef,
      id: id,
    }
  }

  render(): React.ReactNode {
    const {children, hover} = this.props
    return (
      <DropdownContext.Provider value={this.getContextValue()}>
        <div ref={this._containerRef} className={'dropdown ' + (hover ? 'hover-' + hover : '')}>
          {children}
        </div>
      </DropdownContext.Provider>
    )
  }
}

export {Dropdown}
